#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
战斗管理器
负责多对多战斗系统的基础框架
"""

import uuid
import time
from typing import List, Dict, Any, Optional, Tuple
from character.character import Character

class Battle:
    """
    战斗实例
    """
    
    def __init__(self, battle_type: str = "pvp"):
        """
        初始化战斗
        
        Args:
            battle_type: 战斗类型 (pvp, pve, guild_war)
        """
        self.id = str(uuid.uuid4())
        self.battle_type = battle_type
        self.team_a: List[Character] = []
        self.team_b: List[Character] = []
        self.status = "waiting"  # waiting, in_progress, finished
        self.winner = None  # "team_a", "team_b", "draw"
        self.created_at = time.time()
        self.started_at = None
        self.finished_at = None
        self.battle_log: List[str] = []
        
    def add_character_to_team(self, character: Character, team: str) -> bool:
        """
        添加角色到队伍
        
        Args:
            character: 角色对象
            team: 队伍标识 ("a" 或 "b")
            
        Returns:
            是否成功添加
        """
        if self.status != "waiting":
            return False
        
        if character.is_in_battle:
            return False
        
        if team == "a":
            if len(self.team_a) >= 5:  # 最多5人一队
                return False
            self.team_a.append(character)
        elif team == "b":
            if len(self.team_b) >= 5:
                return False
            self.team_b.append(character)
        else:
            return False
        
        character.is_in_battle = True
        character.battle_id = self.id
        return True
    
    def remove_character_from_battle(self, character: Character) -> bool:
        """
        从战斗中移除角色
        """
        if character in self.team_a:
            self.team_a.remove(character)
        elif character in self.team_b:
            self.team_b.remove(character)
        else:
            return False
        
        character.is_in_battle = False
        character.battle_id = None
        return True
    
    def can_start(self) -> bool:
        """
        检查是否可以开始战斗
        """
        return (self.status == "waiting" and 
                len(self.team_a) > 0 and 
                len(self.team_b) > 0)
    
    def start_battle(self) -> bool:
        """
        开始战斗
        """
        if not self.can_start():
            return False
        
        self.status = "in_progress"
        self.started_at = time.time()
        self.battle_log.append(f"战斗开始! 队伍A({len(self.team_a)}人) vs 队伍B({len(self.team_b)}人)")
        return True
    
    def simulate_battle(self) -> str:
        """
        模拟战斗过程（简化版本）
        
        Returns:
            战斗结果
        """
        if self.status != "in_progress":
            return "战斗未开始"
        
        # 计算队伍总战力
        team_a_power = sum(char.attack + char.defense + char.speed for char in self.team_a)
        team_b_power = sum(char.attack + char.defense + char.speed for char in self.team_b)
        
        self.battle_log.append(f"队伍A总战力: {team_a_power}")
        self.battle_log.append(f"队伍B总战力: {team_b_power}")
        
        # 简单的胜负判定（后续可以扩展为回合制战斗）
        import random
        
        # 添加随机因素
        team_a_final = team_a_power * random.uniform(0.8, 1.2)
        team_b_final = team_b_power * random.uniform(0.8, 1.2)
        
        if abs(team_a_final - team_b_final) < min(team_a_final, team_b_final) * 0.1:
            self.winner = "draw"
            result = "平局"
        elif team_a_final > team_b_final:
            self.winner = "team_a"
            result = "队伍A获胜"
        else:
            self.winner = "team_b"
            result = "队伍B获胜"
        
        self.battle_log.append(f"战斗结果: {result}")
        self.status = "finished"
        self.finished_at = time.time()
        
        # 清理角色战斗状态
        for character in self.team_a + self.team_b:
            character.is_in_battle = False
            character.battle_id = None
        
        return result
    
    def get_battle_info(self) -> Dict[str, Any]:
        """
        获取战斗信息
        """
        return {
            'id': self.id,
            'battle_type': self.battle_type,
            'status': self.status,
            'team_a': [char.name for char in self.team_a],
            'team_b': [char.name for char in self.team_b],
            'winner': self.winner,
            'created_at': self.created_at,
            'started_at': self.started_at,
            'finished_at': self.finished_at,
            'battle_log': self.battle_log.copy()
        }

class BattleManager:
    """
    战斗管理器
    """
    
    def __init__(self):
        """
        初始化战斗管理器
        """
        self.battles: Dict[str, Battle] = {}
        self.battle_queue: List[str] = []  # 等待开始的战斗队列
        
        print("战斗管理器初始化完成")
    
    def create_battle(self, battle_type: str = "pvp") -> Battle:
        """
        创建新战斗
        
        Args:
            battle_type: 战斗类型
            
        Returns:
            战斗对象
        """
        battle = Battle(battle_type)
        self.battles[battle.id] = battle
        self.battle_queue.append(battle.id)
        return battle
    
    def get_battle(self, battle_id: str) -> Optional[Battle]:
        """
        获取战斗对象
        """
        return self.battles.get(battle_id)
    
    def join_battle(self, character: Character, battle_id: str, team: str) -> Tuple[bool, str]:
        """
        角色加入战斗
        
        Args:
            character: 角色对象
            battle_id: 战斗ID
            team: 队伍标识
            
        Returns:
            (成功标志, 消息)
        """
        if character.is_in_battle:
            return False, f"{character.name} 已在其他战斗中"
        
        if character.is_idle:
            return False, f"{character.name} 正在挂机中，请先停止挂机"
        
        battle = self.get_battle(battle_id)
        if not battle:
            return False, "战斗不存在"
        
        if battle.status != "waiting":
            return False, "战斗已开始或已结束"
        
        success = battle.add_character_to_team(character, team)
        if success:
            return True, f"{character.name} 成功加入队伍{team.upper()}"
        else:
            return False, "加入战斗失败，队伍可能已满"
    
    def leave_battle(self, character: Character) -> Tuple[bool, str]:
        """
        角色离开战斗
        """
        if not character.is_in_battle:
            return False, f"{character.name} 未在战斗中"
        
        battle = self.get_battle(character.battle_id)
        if not battle:
            return False, "战斗不存在"
        
        if battle.status == "in_progress":
            return False, "战斗进行中无法离开"
        
        success = battle.remove_character_from_battle(character)
        if success:
            return True, f"{character.name} 已离开战斗"
        else:
            return False, "离开战斗失败"
    
    def start_battle(self, battle_id: str) -> Tuple[bool, str]:
        """
        开始战斗
        """
        battle = self.get_battle(battle_id)
        if not battle:
            return False, "战斗不存在"
        
        if not battle.can_start():
            return False, "战斗条件不满足，需要两队都有角色"
        
        success = battle.start_battle()
        if success:
            # 模拟战斗
            result = battle.simulate_battle()
            return True, f"战斗开始并结束，结果: {result}"
        else:
            return False, "开始战斗失败"
    
    def get_available_battles(self) -> List[Dict[str, Any]]:
        """
        获取可加入的战斗列表
        """
        available = []
        for battle in self.battles.values():
            if battle.status == "waiting":
                available.append(battle.get_battle_info())
        return available
    
    def get_battle_history(self, limit: int = 10) -> List[Dict[str, Any]]:
        """
        获取战斗历史
        """
        finished_battles = []
        for battle in self.battles.values():
            if battle.status == "finished":
                finished_battles.append(battle.get_battle_info())
        
        # 按结束时间排序
        finished_battles.sort(key=lambda x: x['finished_at'] or 0, reverse=True)
        return finished_battles[:limit]
    
    def cleanup_old_battles(self, max_age_hours: int = 24):
        """
        清理旧的战斗记录
        """
        current_time = time.time()
        max_age_seconds = max_age_hours * 3600
        
        battles_to_remove = []
        for battle_id, battle in self.battles.items():
            if (battle.status == "finished" and 
                battle.finished_at and 
                current_time - battle.finished_at > max_age_seconds):
                battles_to_remove.append(battle_id)
        
        for battle_id in battles_to_remove:
            del self.battles[battle_id]
            if battle_id in self.battle_queue:
                self.battle_queue.remove(battle_id)
        
        return len(battles_to_remove)